<?php

class OdnoklassnikiService  extends Auth
{
    public $clientId='';
    public $clientPublic='';
    public $clientSecret='';
    protected $token='';
    protected $userInfo=false, $serviceName='odnoklassniki';

    public function getUserInfo()
    {
        $info=$this->userInfo;

        return array(
            'user'=>array(
                'login'=>isset($info->uid) ? $info->uid : '',
                'userName'=>isset($info->uid) ? $info->uid : '',
                'password'=>'',
                'confirmCode'=>'',
                'email'=>'',
                'isConfirmed'=>1,
                'isActive'=>1,
            ),
            'profile'=>array(
                'firstName'=>isset($info->first_name) ? $info->first_name : '',
                'lastName'=>isset($info->last_name) ? $info->last_name : '',
                'sex'=>isset($info->gender) ? ($info->gender!='male' ? 1 : 0) : 0,
                'img'=>isset($info->pic_1) ? $info->pic_1 : (isset($info->pic_2) ? $info->pic_2 : ''),
                'birthday'=>isset($info->birthday) ? $info->birthday : NULL,
            ),
        );
    }

    public function getToken()
    {
        return $this->token;
    }

    public function getServiceName()
    {
        return $this->serviceName;
    }

    public function firstRequest()
    {
        $redirectUrl='http://www.odnoklassniki.ru/oauth/authorize?client_id='.$this->clientId.
            '&response_type=code&redirect_uri='.$this->getReturnUrl();

        Yii::app()->request->redirect($redirectUrl);
    }

    public function secondRequest()
    {
        if($code=Yii::app()->request->getQuery('code')){

            $bodyParams='code='.$code.
                '&redirect_uri='.$this->getReturnUrl().
                '&grant_type=authorization_code&client_id='.$this->clientId.
                '&client_secret='.$this->clientSecret;

            $post=Yii::app()->post->open('http://api.odnoklassniki.ru/oauth/token.do','curl',80);
            $post->body=$bodyParams;

            if($post->sendRequest() && $this->token=$post->result->access_token){
                $sign=md5('application_key='.$this->clientPublic.'method=users.getCurrentUser'.md5($this->token.$this->clientSecret));

                $redirectUrl='http://api.odnoklassniki.ru/fb.do?method=users.getCurrentUser&access_token='.$this->token.
                    '&application_key='.$this->clientPublic.
                    '&sig='.$sign;

                if(is_object($result=json_decode(file_get_contents($redirectUrl)))){
                    if(isset($result->error_msg)) $this->quit($result->error_msg);
                    $this->userInfo=$result;
                    return true;
                }
            }else{
                $this->quit('Не удалось отправить POST-запрос: '.$post->error);
            }
        }

        return false;
    }
}